package com.singzi.leetcode.jianzhiOffer2;

public class T0010 {
    public static void main(String[] args) {
        int []nums = {1,1,0,0,0,1};
        int k = 2;
        Solution0010 solution0010 = new Solution0010();
        System.out.println(solution0010.subarraySum(nums, k));
    }
}
class Solution0010 {
    public int subarraySum(int[] nums, int k) {
        int left = 0, right = 0, sum = nums[right];
        int ans = 0;
        while(right < nums.length){
            if(sum == k){
                ans++;
                while (left <= right){
                    if(nums[left] != 0) break;
                    else {
                        ans++;
                        left++;
                    }
                }
                while (right < nums.length) {
                    if (nums[right] != 0) break;
                    else {
                        ans++;
                        right++;
                    }
                }
                right++;
                sum += nums[right];
            }
            while(sum < k && right < nums.length){
                right++;
                if(right < nums.length) sum += nums[right];
            }
            while(sum > k){
                sum-= nums[left];
                left++;
            }
        }
        return ans;

    }
}